﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace YXChatApiService.HubCommon
{
    public class ChatHub:Hub<IChatService>
    {
        public override Task OnConnectedAsync()
        {
            Console.WriteLine(Context.ConnectionId);
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            var client = HubClients.AccountClients.FirstOrDefault(n => n.ConnectionId == Context.ConnectionId);
            if (client != null)
            {
                HubClients.AccountClients.Remove(client);
                Console.WriteLine($"remove :{client.ConnectionId}");
            }
            return base.OnDisconnectedAsync(exception);
        }

        public void AddClient(string accountNumber)
        {
            HubClients.AccountClients.Add(new AccountClient()
            {
                AccountNumber = accountNumber,
                ConnectionId = Context.ConnectionId
            });
        }
    }

    public class HubClients
    {
        public static Dictionary<string, string> allClient = new Dictionary<string, string>();
        public static List<AccountClient> AccountClients = new List<AccountClient>();
    }

    public class AccountClient
    {
        public string AccountId { get; set; }
        public string AccountNumber { get; set; }
        public string ConnectionId { get; set; }
    }
}
